<template>
  <el-upload
    :action="uploadUrl"
    multiple
    :headers="headers"
    :on-success="onSuccess"
    :show-file-list="false"
    class="upload"
    ref="uploadRef"
    :disabled="disabled"
    :style="style"
  >
    <el-popover placement="bottom" :width="200" trigger="hover">
      <template #reference>
        <el-button class="btn">
          <span class="text">
            <div></div>
            {{ $t('lang.form.fileList') }}
            <i class="el-icon-arrow-down" />
          </span>
        </el-button>
      </template>
      <div class="file-list" v-if="fileList.length">
        <div v-for="file of fileList" :key="file.uid" class="file">
          <i class="el-icon-document icon" />
          <el-link type="info" :key="file.uid" @click.prevent="downloadFile(file)">
            {{ file.name }}
          </el-link>
          <div class="operate">
            <el-icon
              v-if="isPreview(file)"
              class="el-icon-picture-outline preview"
              @click="onPreivew(file)"
            />
            <el-icon v-if="!disabled" class="el-icon-close icon delete" @click="deleteFile(file)" />
          </div>
        </div>
      </div>
      <div v-else class="no-data">{{ $t('lang.form.noData') }}</div>
    </el-popover>
    <!-- <el-button type="primary" v-if="!disabled" :loading="loading" @click="loading = true">
      {{ $t('lang.operate.upload') }}
    </el-button> -->
  </el-upload>
  <preivew v-model="previewInfo.visible" :file-id="previewInfo.fileId" />
</template>

<script lang="ts">
import { defineComponent, ref, PropType, watch, reactive } from 'vue'
import { getToken } from '@/utils/auth'
import { CHECC_API_FAST_DFS } from '@/constants/proxy'
import { get, remove, map, last } from 'lodash'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
import { Upload } from '../../types'
import * as api from '@/api/file'
import Preivew from './Preview.vue'
import { ObjectType } from 'typings/interfaces'

interface File {
  name: string
  uid: number
  row: any
  response: {
    data: {
      path: string
      fileId: string
      fileName: string
      type: string | undefined
    }
  }
}

export default defineComponent({
  components: {
    Preivew,
  },
  props: {
    disabled: {
      type: Boolean,
      required: true,
    },
    item: {
      type: Object as PropType<Upload>,
      required: true,
    },
    form: {
      type: Object as PropType<ObjectType>,
      required: true,
    },
  },
  setup(props) {
    const fileList = ref<File[]>([])
    const loading = ref(false)
    const uploadRef = ref(null)
    const previewInfo = reactive({
      visible: false,
      fileId: '',
    })
    const { t } = useI18n()
    const deleteFile = (file: File) =>
      api.deleteFileRequset(get(file, 'response.data.fileId')).then(() => {
        ElMessage({
          type: 'success',
          message: t('lang.operate.deleteSuccess'),
        })
        remove(get(fileList, 'value', []), {
          uid: file.uid,
        })
      })

    const canInit = ref(true)
    const onSuccess = (response, file) => {
      ElMessage({
        type: 'success',
        message: t('lang.operate.updateSuccess'),
      })
      loading.value = false
      fileList.value.push(file)
      canInit.value = false
      // fileList.value = get(uploadRef, 'value.uploadFiles')
    }

    watch(
      fileList,
      (list) => {
        props.form[props.item.key] =
          list.length === 1 ? [list[0].response.data] : map(list, (item) => item.response.data)
      },
      { deep: true }
    )

    watch(
      () => props.form[props.item.key],
      (data) => {
        if (canInit.value) {
          fileList.value = map(data, (file) => ({
            name: file.fileName,
            uid: file.fileId,
            row: '',
            response: {
              data: {
                fileId: file.fileId,
                fileName: file.fileName,
                path: '',
                type: last(file.fileName.split('.')),
              },
            },
          }))
          canInit.value = false
        }
      },
      { deep: true }
    )

    const onPreivew = (file: File) => {
      previewInfo.visible = true
      previewInfo.fileId = get(file, 'response.data.fileId')
    }

    const isPreview = (file: File) => {
      const fileType = get(file, 'response.data.type', '')
      const imageTypes = ['png', 'jpg', 'gif', 'svg']
      return imageTypes.includes(fileType)
    }
    return {
      deleteFile,
      fileList,
      uploadRef,
      onSuccess,
      loading,
      previewInfo,
      onPreivew,
      uploadUrl: CHECC_API_FAST_DFS + '/file/upload',
      headers: {
        Authorization: 'Bearer ' + getToken(),
      },
      style: {
        width: props.item?.width ? props.item.width + 'px' : '100%',
      },
      isPreview,
      downloadFile: (file: File) => api.downloadFileRequest(get(file, 'response.data.fileId')),
    }
  },
})
</script>

<style scoped lang="scss">
.upload {
  width: 200px;
  :global(.el-upload) {
    display: flex;
  }
  .btn {
    width: 100%;
    flex: 1;
    .text {
      display: flex;
      justify-content: space-between;
    }
  }
}
.file-list {
  display: flex;
  flex-direction: column;
  .file {
    width: 100%;
    display: flex;
    align-content: center;
    margin: 4px 0;
    &:hover {
      background-color: #f5f7fa;
      a {
        color: #66b1ff;
        &::after {
          color: #66b1ff;
        }
      }
    }
    a {
      margin-left: 4px;
    }
    .icon {
      cursor: pointer;
      &:before {
        vertical-align: sub;
      }
    }
  }
}

.operate {
  width: 36px;
  margin-left: auto;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.preview:hover {
  color: #409eff;
}
.delete {
  display: flex;
  margin-left: auto;
  &:hover {
    color: red;
  }
}
.no-data {
  text-align: center;
}
</style>
